/**
 * 排名图（符号为圆，圆的大小表示数值的大小）
 *//**
* 象形符号等级专题图
* 说明：表达意义同等级符号专题图，符号不再是圆，
* 而是根据指标进行推荐响应的图形，如人口数用人
* 展示，企业数用企业图表展示等
*/
import echarts from 'echarts'; // echarts 文件引入
import sgisLayerBase from '../../sfgis.layer.base';
import colorPicker from '../macrolayers/echarts.colorpicker'; // 颜色初始化配置文件
import styleModify from '../macrolayers/echarts.stylemodify.js';
import store from "../../../../pages/macro/store";
import { getMapLayers } from "vuex";

export default {
    layerNum: 0, // 麻点图多能叠加10个，过多时提示移除，防止太卡
    rankingLayer: '',
    rankingLayerInfo: {},
    maxValue:"",
    callback: "",
    colors: [
        "#EE7600",
        "#88E3CD",
        "#CD8C95",
        "#458B00",
        "#00EE76",
        "#A02395",
        "#00CDCD",
        "#00868B",
        "#CD5555",
        "#FF0000"
    ], // 麻点图配色方案
    /**
     * 创建专题图
     * @param {Object} map 地图实例
     * @param {Object} data 用于创建专题图的数据
     *      {
     *        "id": "", 专题图的id
     *        "name": "", 专题图的名称
     *        "datas": [
     *          {id:"",name:"",lon:"",lat:"",regioncode:"",regionname:""},{}
     *        ]
     *      }
     */

    createLayer(map, data, callback) {
        this.maxValue = Math.ceil((data.data[0].value[2]) / 50);
        if (map.overlayers["ranking"] && map.overlayers["ranking"] != "layer") {
            map.overlayers["ranking"][0].remove();
        }
        this.callback = callback;
        // 圆的大小 // 鼠标进入时的动态效果 // 颜色要动态改变 // 鼠标进入时的颜色
        let rankingMarkers = this.createMarker(data.data, map);
        const rankingLayer = rankingMarkers;

        this.createCharts(rankingMarkers, data.data, data.name, data.image);
        rankingMarkers[0].chart.on("mousemove", function (params) {
            EventBus.$emit("table-actiontrigger", {
                regionCode: params.data.region
            });
            EventBus.$emit("onChart-action", { regionCode: params.data.region });
        });
        rankingMarkers[0].chart.on("mouseout", function (params) {
            EventBus.$emit("table-heighLightOff", {
                regionCode: params.data.region
            });
            EventBus.$emit("offChart-action", { regionCode: params.data.region });
        });
        this.rankingLayer = rankingLayer;
        this.layerNum++;
        rankingLayer.setVisible = this.setVisible; // 添加设置可见性函数
        rankingLayer.setOpacity = this.setOpacity; // 添加设置图层透明度函数
        rankingLayer.setZIndexOffset = this.setZIndexOffset; // 设置图层顺序函数
        rankingLayer.calgraph = this.calgraph; // 添加计算图例函数
        this.rankingLayerInfo.layerId = "ranking";
        styleModify.onZoomScatter(map, rankingLayer, this.rankingLayerInfo.layerId); // 由于麻点图在放大平移时均会改变可见性，故有此函数
        rankingLayer.layerId = "ranking";
        styleModify.layerOrder[this.rankingLayerInfo.layerId] = styleModify.curZindex;
        styleModify.curZindex -= 1;

        this.rankingLayerInfo.name = data.name;
        this.rankingLayerInfo.type = 'ranking';
        this.rankingLayerInfo.show = data.showThumbnails !== false;

        store.commit("getMapLayers", this.rankingLayerInfo)
        map.overlayers["ranking"] = rankingLayer
        map.overlayerInfos["ranking"] = this.rankingLayerInfo

        return this.rankingLayerInfo;
    },
    createMarker(datas, map) {
        const time = +new Date();
        const resultMarkers = [];
        let rankingMaker = new EchartsLayer(map);
        rankingMaker._container.className = "chart_fullscreen"
        rankingMaker._container.id = "ranking_chart_" + time;
        rankingMaker._container.style['position'] = "fixed";
        resultMarkers.push(rankingMaker);
        return resultMarkers;
    },
    createCharts(rankingLayer, datas, name, image) {
        if (datas.length <= 5) {
            let i = 1;
            let optionTimer = setInterval(() => {
                let dataValue = datas.slice(0, i)
                let option = {
                    color: store.state.macro.layerColors["ranking"] ? store.state.macro.layerColors["ranking"] : ["#1B9E77"],
                    animation: false,
                    tooltip: {
                        formatter: function (params) {
                            return `${params.name}:${params.value[2]}`;
                        }
                    },
                    GLMap: {},
                    series: [{
                        name: name,
                        type: 'scatter',
                        coordinateSystem: 'GLMap',
                        data: dataValue,
                        symbol: 'pin', //气泡
                        symbolSize:  (val)=> {
                            if (parseInt(val[2] / this.maxValue) >= 50) {
                                return 50
                              } else if (parseInt(val[2] / this.maxValue) <= 30) {
                                return 30
                              } else {
                                return parseInt(val[2] / this.maxValue)
                              }
                        },
                        label: {
                            normal: {
                                show: true,
                                textStyle: {
                                    color: '#fff',
                                    fontSize: 9,
                                },
                                formatter: function (params) {
                                    return params.dataIndex + 1;
                                },
                            }
                        },
                        tooltip: {
                            trigger: 'item',
                            formatter: function (params) {
                                return params.name + ' : ' + params.value[2];
                            },
                        },
                    }]
                };
                rankingLayer[0].chart.setOption(option);
                i++;
                if (i > datas.length) {
                    this.rankingLayerInfo.html = this.calgraph(this.rankingLayer, this.rankingLayerInfo.layerId, image);
                    // 为当前layer绑定设置颜色的方法
                    this.rankingLayer.setCustomColor = this.setCustomColor;
                    sgisLayerBase.setOverLayers(this.rankingLayerInfo);
                    this.callback(this.rankingLayerInfo)
                    clearInterval(optionTimer)
                }
            }, 500)
        } else {
            let i = 5;
            let optionTimer = setInterval(() => {
                let dataValue = datas.slice(0, i)
                let option = {
                    color: store.state.macro.layerColors["ranking"] ? store.state.macro.layerColors["ranking"] : ["#1B9E77"],
                    animation: false,
                    tooltip: {
                        formatter: function (params) {
                            return `${params.name}:${params.value[2]}`;
                        }
                    },
                    GLMap: {},
                    series: [{
                        name: name,
                        type: 'scatter',
                        coordinateSystem: 'GLMap',
                        data: dataValue,
                        symbol: 'pin', //气泡
                        symbolSize: function (val) {
                            if (val[2] / 10 >= 50) {
                                return 50
                            } else if (val[2] / 10 <= 30) {
                                return 30
                            } else {
                                return val[2] / 10
                            }
                        },
                        label: {
                            normal: {
                                show: true,
                                textStyle: {
                                    color: '#fff',
                                    fontSize: 9,
                                },
                                formatter: function (params) {
                                    return params.dataIndex + 1;
                                },
                            }
                        },
                        tooltip: {
                            trigger: 'item',
                            formatter: function (params) {
                                return params.name + ' : ' + params.value[2];
                            },
                        },
                    }]
                };
                rankingLayer[0].chart.setOption(option);
                i += 5;
                if (i-datas.length > 5) {
                    this.rankingLayerInfo.html = this.calgraph(this.rankingLayer, this.rankingLayerInfo.layerId, image);
                    this.callback(this.rankingLayerInfo)
                    this.rankingLayer.setCustomColor = this.setCustomColor;
                    sgisLayerBase.setOverLayers(this.rankingLayerInfo);
                    clearInterval(optionTimer)
                }
            }, 500)
        }



    },
    /**
     *
     * @param {Object} laryer
     * @param {String} colorParam
     */
    setCustomColor(laryer, colorParam) {
        const options = laryer[0].chart.getOption();
        options.color = [colorParam.colors[colorParam.colors.length - 1]]
        store.commit("layerColors", { type: "ranking", color: [colorParam.colors[colorParam.colors.length - 1]] })
        laryer[0].chart.setOption(options);
        laryer.calgraph(laryer, laryer.layerId);
    },
    /* *图层样式可见性设置函数 */
    setVisible(visible) {
        styleModify.setScatterVisible(visible, this.layerId, this[0]);
    },
    /* *设置图层透明度 */
    setOpacity(opacity) {
        this[0]._container.style.opacity = opacity;
    },
    /** 设置调整图层顺序函数*/
    setZIndexOffset(index) {
        styleModify.setZIndexOffset(index, this.layerId, this[0]);
    },
    /* *图例样式计算 */
    calgraph(rankingLayer, layerId) {
        let mark_item = [];
        let layer_list = rankingLayer[0].chart.getOption().series
        for (let i = 0; i < layer_list.length; i++) {
            let str = {
                name: layer_list[i].name,
                color: rankingLayer[0].chart.getOption().color[i]
            }
            mark_item.push(str)
        }
        let html = `<div style="padding:10px" class="${layerId}">`;
        for (const key in mark_item) {
            html += `<div class='chart_item' style='display:flex;align-items: center;justify-content: flex-start;'>
      <div style='display:inline-block;width:10px;height:10px;border-radius:100%;background:${mark_item[key].color}'>
        
      </div>
        <p>&nbsp;&nbsp;&nbsp;&nbsp;${mark_item[key].name}</p>
      </div>`;
        }
        html += '</div>';
        let layers = sgisLayerBase.overLayers;
        layers.map(item => {
            if (item.type == layerId) {
                item.html = html
            }
        })
        return html;
    },
    autoCalgraph(layerId, color) {
        const itemColor = color;
        const emphsisColor = 'red';
        const html = `
     <div class="${layerId}" style='text-align:center;padding:10px;'>
        <div style='display:inline-block;width:10px;height:10px;background:${itemColor};border-radius:10px' onmouseover="this.style.background='${emphsisColor}'" onmouseout="this.style.background='${itemColor}'"></div>
        <div style='display:inline-block;width:10px;height:10px;background:${itemColor};border-radius:10px;' onmouseover="this.style.background='${emphsisColor}'" onmouseout="this.style.background='${itemColor}'"></div>
        <div style='width:10px;height:10px;background:${itemColor};border-radius:10px' onmouseover="this.style.background='${emphsisColor}'" onmouseout="this.style.background='${itemColor}'"></div>
     </div>
    `;
        const layers = sgisLayerBase.overLayers;
        for (const key in layers) {
            if (layers[key].layerId === layerId) {
                layers[key].html = html;
            }
        }
    }
};
